home *** CD-ROM | disk | FTP | other *** search
- Path: mail2news.demon.co.uk!txwang
- From: Wang TianXing <gztxwang@public1.guangzhou.gd.cn>
- Newsgroups: comp.lang.c++
- Subject: Re: object creation from an abstract base class
- Date: Sun, 24 Mar 1996 10:54:23 GMT
- Message-ID: <199603232309.HAA23055@public1.guangzhou.gd.cn>
- X-NNTP-Posting-Host: txwang
- X-Newsreader: Forte Free Agent 1.0.82
- X-Mail2News-Path: public1.guangzhou.gd.cn!txwang
-
- On 23 Mar 1996 18:22:26 GMT, grantp@usa.pipeline.com(Pete Grant)
- wrote:
-
- | On Mar 21, 1996 08:59:50 in article <Re: object creation from an abstract
- | base class>, 'Sukanta Ganguly <sukanta_ganguly@novell.com>' wrote:
- |
- |
- | >Michael Catello wrote:
- | >>
- | >> Hello OOPsters,
- | >>
- | >> I was just looking for validation/other suggestions for a method I
- | >> recently used in a program. I have defined an abstract base class
- | >> (i.e. contains pure virtual functions), all access to the derived
- | >> classes of this base are thru a pointer to the base class. To create
- | >> the actual objects of the derived classes I used the following scheme:
- | >>
- | >> enum FooType {BAR, BAS};
- | >>
- | >> // base class
- | >> class CFoo
- | >> {
- | >> CFoo();
- | >> ~CFoo();
- | >>
- | >> static CFoo* CreateFoo(FooType type);
- | >>
- | >> // other methods/data including pure virtual fns whose behaviour
- |
- | >will
- | >> be defined in the derived classes
- | >> };
- | >>
- | >> class CBar: public CFoo
- | >> {
- | >> //
- | >> };
- | >>
- | >> class CBas: public CFoo
- | >> {
- | >> //
- | >> };
- | >>
- | >> CFoo* CFoo::CreateFoo(FooType type)
- | >> {
- | >> CFoo* pfoo = NULL;
- | >>
- | >> switch (type)
- | >> {
- | >> case BAR:
- | >> pfoo = new CBar;
- | >> break;
- | >> case BAS:
- | >> pfoo = new CBas;
- | >> break;
- | >> }
- | >>
- | >> return pfoo;
- | >> }
- | >>
- | >> main()
- | >> {
- | >> CFoo* interface = CFoo::CreateFoo(BAR);
- | >> }
- | >>
- | >> Obviously it is the CreateFoo() function that I am wondering about. In
- | >> the actual implementation I had multiple static "Create" functions for
- | >> the base class that would allow me to create a new object: one based
- | >> on an enumerated token (shown above), another an existing object, as
- | >> well as one based on the format of a datafile. My application never
- | >> references any of the derived classes directly, except in their
- | >> creation and definition.
- | >>
- | >> Is there another/better/more appropriate way to handle this type of
- | >> object creation? Thanks for your assistance,
- | >>
- | > [incorrect things deleted]
- |
- | BTW, the statement "pfoo = new CBas;" is perfectly legal,
- | and even proper. Any compiler that "cribs" about it is wrong.
-
- So, the original poster should write code like this:
-
- CFoo *interface = new CBar;
-
- and remove the static function CFoo::CreateFoo(FooType);
-
- ---
- Wang TianXing
-
-
-